var used_second;
var timer;
function ouput(){
    used_second = used_second + 1;
    $('#time').text(formatSeconds(used_second));
}

/**
* 将秒数换成时分秒格式
* 整理：www.jbxue.com
*/

function formatSeconds(value) {
    var theTime = parseInt(value);// 秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    if(theTime > 60) {
        theTime1 = parseInt(theTime/60);
        theTime = parseInt(theTime%60);
            if(theTime1 > 60) {
            theTime2 = parseInt(theTime1/60);
            theTime1 = parseInt(theTime1%60);
            }
    }
        var result = ""+parseInt(theTime)+"秒";
        if(theTime1 > 0) {
        result = ""+parseInt(theTime1)+"分"+result;
        }
        if(theTime2 > 0) {
        result = ""+parseInt(theTime2)+"小时"+result;
        }
    return result;
}

function process(id, msg){
	$table = $('#myModal #check_table tbody');
	var bar = $('#myModal .progress .bar');
	//处理完毕
	if(id == -1){
		$('#check_status label').text('检测完毕').after(' <a href="javascript:new_win();">新窗口查看</a>');
		bar.width('100%');
		//停止计时，限时完成
        clearInterval(timer);
	}else{
        var total = $('#counting').data('total');
        var now = id+2> total? total: id+2
        $('#counting').text(now+'/'+total );
		bar.width(function(index, width){
 			return now/total*100+'%';
 		});
		$table.append(msg);
		$.ajax({
			url: check_url,
			type: 'GET',
			data:{id:id+1},
			timeout:10000,
			// async: false,
			success:function(data){
                eval(data);
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
                $('#myModal').html('网络出错了');
            }
	 	});
	}
}

function new_win(){
    var about_blank = window.open('about:blank',"new_win");
    about_blank.document.write('<link href="http://libs.useso.com/js/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">');
    about_blank.document.write($('#check_table').prop('outerHTML'));
}

$(function(){
	var $urls = $('#urls');
	$checkBtn = $('#check');
	$cleanBtn = $('#clean');
	$rulesBtn = $('#rules');

	$urls.on('keyup', function(){
		if($.trim($urls.val()) != ''){
            $cleanBtn.attr('disabled', false);
			$checkBtn.attr('disabled', false);
        }
	});
    $cleanBtn.on('click', function(){
        $urls.val('');
    });
	//获取书签规则
	$.getJSON(rules_url, function(json, textStatus) {
		var options = json;
		var $rules = $('#rules');
		$.each(options, function(index, val) {
			$rules.append('<option value="'+index+'">'+val+'</option>');
		});
	});
	//检测
	$checkBtn.on('click', function(){
		var urls = $.trim($urls.val());
		if('' != urls){
            used_second = 0;
            ouput();
			$('#myModal').html($('#loading_tpl').html());
			$('#check_table tbody').html('');
			$('#myModal').modal('show');
            var total = urls.split('\n').length;
            $('#counting').text('1/'+total);
            $('#counting').data('total', total);
		}
	});

	$('#myModal').on('shown.bs.modal', function (e) {
        timer = window.setInterval("ouput()", 1000);
		$.ajax({
            type: 'POST',
            url: check_url,
            data: {urls:$.trim($urls.val())},
            success:function(data){
				eval(data);
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
                $('#myModal').html('网络出错了');
            }
        });
    }).on('hidden.bs.modal',function(e){
        $(this).removeData('bs.modal');
    });

    //上传书签
    $("#upload_win_btn").uploadify({
    	"height"          : 45,
        "swf"             : uploadify_swf,
        "fileObjName"     : "bookmark_upload",
        "buttonImage"     : uploadify_btn_img,
        "formData"        : {
            'session_id'  :session_id,
        },
        "queueSizeLimit"  : 1,
        "uploader"        : uploader,
        "width"           : 264,
        "removeTimeout"   : 1,
        "fileSizeLimit"   : 0,
        "fileTypeExts"    : "*.*",
        "onInit":function(){

        },
        "onFallback" : function() {
        	alert('未检测到兼容版本的Flash.');
        },
        "onUploadSuccess" : function(file, data){
            if (data != 0){
            	var rule = $('#rules').val();
            	if('' != rule){
            		$html = $(data);
            		$links = $html.find(rule);
            		var data = [];
            		$links.each(function(index, el) {
            			data.push($.trim(el.href));
            		});
            		data = data.join('\n');
            	}
            	$urls.val(data);
                $cleanBtn.attr('disabled', false);
            	$checkBtn.attr('disabled', false);
            } else {
            	alert(data.info);
            }
        }
    });
});